package uk.ac.sanger;

import java.sql.*;
import javax.sql.DataSource;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletContextListener;
import javax.servlet.ServletContext;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;


import javax.servlet.*;
import javax.servlet.http.*;


public class test_conn extends HttpServlet implements ServletContextListener{
	DataSource  ds;
	
	public void contextInitialized (ServletContextEvent sce){
		try {
			// Obtain our environment naming context
			//Context envCtx = (Context) new InitialContext().lookup("java:comp/env");

			System.out.println("context initialized method");
			
			
			// Look up our data source
			//ds = (DataSource) envCtx.lookup("jdbc/TestDB");

			//sce.getServletContext().setAttribute("DBCPool", ds);
		} catch(Exception  e){ e.printStackTrace();
		}
	}

	public void init() throws ServletException {
		try {
			//Create a datasource for pooled connections.
			//datasource = (DataSource) getServletContext.getAttribute("DBCPool");
			
			System.out.println("init method");
			
			//Register the driver for non-pooled connections.
			Class.forName("com.mysql.jdbc.Driver").newInstance();
		}
		catch (Exception e) {
			throw new ServletException(e.getMessage());
		}
	}

	private synchronized Connection getConnection (boolean pooledConnection)
	throws SQLException {
		int pooledCount, nonpooledCount;
		pooledCount=0;
		nonpooledCount=0;
		
		System.out.println ("getconnection " +pooledCount);
		
		if (pooledConnection) {
			pooledCount++;
			// Allocate and use a connection from the pool
			return ds.getConnection();
		}
		else {
			nonpooledCount++;
			Connection con = DriverManager.getConnection(
					"ensdb-1-07.internal.sanger.ac.uk","admin","-pensembl");
			return con;   //return a newly created object
		}
	}
	public void doGet(HttpServletRequest request,
	        HttpServletResponse response)
	        throws IOException, ServletException
	{
	    try
	    {
	    	response.setContentType("text/html");
	        PrintWriter out = response.getWriter( );
	        out.println ("<html><body>Hello111 new World!</body></html>");
		    
	        System.out.println ("Before " );
	        
	        //Connection conn = getConnection(true);
		    //Statement stat = conn.createStatement();

            //System.out.println ("Information :");
            //ResultSet rs = stat.executeQuery ("SELECT * FROM source_00001063");
            //while(rs.next())
            {
            //	System.out.println ("Name: " +	rs.getString("featureid"));
            }
	     }
	catch (Exception e) 
    {
            System.err.println(e);
            System.exit(2);
     }
	}

	public void contextDestroyed(ServletContextEvent sce)
	{
	}
}

